﻿using Paine.SolidWorks.Base;
using System;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using SolidWorks.Base;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using View = SolidWorks.Interop.sldworks.View;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using TextBox = System.Windows.Forms.TextBox;

namespace Paine.SolidWorks.Exe
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            cobSolidWorksVersion.Items.Clear();
            var allVersion = Connect.GetSolidWorksYears();
            foreach (var version in allVersion)
            {
                cobSolidWorksVersion.Items.Add(version);
            }

            cobSolidWorksVersion.SelectedIndex = 0;
        }

        /// <summary>
        /// 打开solidworks
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                if (Connect.IsRunning())
                {
                    if (MessageBox.Show($@"SolidWorks 进行已经存在，是否要继续", @"确定", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    {
                        return;
                    }
                }

                var intVer = Connect.ConvertYearToMajorVersion((int.Parse(cobSolidWorksVersion.Text)));

                var swExePath = Connect.GetSolidWorksExecutablePath(intVer);

                MessageBox.Show($@"SolidWorks{cobSolidWorksVersion.Text} 本机路径为{swExePath}");

                var swApp = Connect.RunSolidWorks(intVer, true);

                if (swApp != null)
                {
                    MessageBox.Show($@"SolidWorks{cobSolidWorksVersion.Text} 已经成功启动");
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show($@"{exception.StackTrace}");
            }
        }

        /// <summary>
        /// 连接正在运行的SolidWorks
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetSolidWorks_Click(object sender, EventArgs e)
        {
            try
            {
                var swApp = Connect.GetRunningSolidWorks();

                if (swApp != null)
                {
                    swApp.GetBuildNumbers2(out string baseVersion, out _, out _);

                    MessageBox.Show($@"已经成功连接到SolidWorks,版本为:{baseVersion}");
                }
                else
                {
                    MessageBox.Show($@"请检查是否已经启动SolidWorks");
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show($@"{exception.StackTrace}");
            }
        }

        /// <summary>
        /// 关闭所有SolidWorks
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCloseAll_Click(object sender, EventArgs e)
        {
            Connect.IsRunning(true);
        }

        /// <summary>
        /// 浏览文件并打开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBrowseAndOpen_Click(object sender, EventArgs e)
        {

            var ofd = new OpenFileDialog();
            ofd.InitialDirectory = "";
            ofd.Filter = @"SolidWorks files|*.SLDPRT;*.SLDASM,*.SLDDRW|x_t step stp files|*.x_t;*.stp;*.step";
            ofd.FilterIndex = 1;
            ofd.Multiselect = false;
            ofd.RestoreDirectory = true;
            if (ofd.ShowDialog() != DialogResult.OK) return;

            txtFilePath.Text=ofd.FileName;
            SldWorks swApp;
            swApp = null;
            if (Connect.IsRunning())
            {
                swApp = Connect.GetRunningSolidWorks();

            }
            else
            {
                var intVer = Connect.ConvertYearToMajorVersion((int.Parse(cobSolidWorksVersion.Text)));

                swApp = Connect.RunSolidWorks(intVer, true);

            }

            if (swApp!=null)
            {
                var swModel= swApp.OpenExistFile(txtFilePath.Text, out int openErr, out int warn, out int activateErr);

                if (swModel!=null)
                {
                    MessageBox.Show(@"文件已经打开。");
                }
            }
            else
            {
                MessageBox.Show(@"未能获取到SolidWorks。");
            }



        }

        private void btnOpenPropertiesEdit_Click(object sender, EventArgs e)
        {
            try
            {
                var swApp = Connect.GetRunningSolidWorks();

               

                if (swApp == null )
                {
                    MessageBox.Show($@"请检查是否已经启动SolidWorks,并打开一个文件。");

                    return;
                }

                var swModel = swApp.IActiveDoc2;

                if (swModel!=null)
                {
                    try
                    {
                        this.Visible =false;

                        var FrmPropertiesEdit = new FrmPropertiesEdit(swModel);

                        FrmPropertiesEdit.ShowDialog(this);

                    }
                    finally
                    {

                        this.Visible = true;
                    }
                   



                    //MessageBox.Show($@"当前文件所有属性数量{allProperties.Sum(x=>x.PropertyItems.Count)}");


                }


            }
            catch (Exception exception)
            {
                MessageBox.Show($@"{exception.StackTrace}");
            }
        }

        private void btnFeatrueTree_Click(object sender, EventArgs e)
        {
            try
            {
                var swApp = Connect.GetRunningSolidWorks();



                if (swApp == null)
                {
                    MessageBox.Show($@"请检查是否已经启动SolidWorks,并打开一个文件。");

                    return;
                }

                var swModel = swApp.IActiveDoc2;

                if (swModel != null)
                {
                    try
                    {
                        this.Visible = false;

                        var FrmFeatureTree = new FrmFeatureTree(swApp,swModel);

                        FrmFeatureTree.ShowDialog(this);

                    }
                    finally
                    {

                        this.Visible = true;
                    }




                 
                }


            }
            catch (Exception exception)
            {
                MessageBox.Show($@"{exception.StackTrace}");
            }
        }

        private void btnGetSelectFeatureInfo_Click(object sender, EventArgs e)
        {
            try
            {
                var swApp = Connect.GetRunningSolidWorks();



                if (swApp == null)
                {
                    MessageBox.Show($@"请检查是否已经启动SolidWorks,并打开一个文件。");

                    return;
                }

                var swModel = swApp.IActiveDoc2;

                if (swModel != null)
                {
                    try
                    {

                        var swMgr = swModel.ISelectionManager;

                        var selObj = swMgr.GetSelectedObject6(1,-1);

                        if (selObj is Feature selFea)
                        {
                            var allFaces = (object[])selFea.GetFaces();

                            for (var index = 0; index < allFaces.Length; index++)
                            {
                                var face = allFaces[index] as Face2;

                                if (face != null)
                                {
                                    txtInfo.Text = $@"Face {index} 面积: " + face.GetArea() + System.Environment.NewLine + txtInfo.Text;

                                    var faceNormal = (double[])face.Normal;


                                    txtInfo.Text = $@"Face {index} 法向量: {faceNormal[0]},{faceNormal[1]},{faceNormal[2]}"  + System.Environment.NewLine + txtInfo.Text;

                                    var edges = (object[])face.GetEdges();

                                    for (int i = 0; i < edges.Length; i++)
                                    {
                                        var edge = edges[i] as Edge;
                                        if (edge!=null)
                                        {
                                            PrintEdgeInfo(edge,txtInfo);

                                            //var stratP = (double[])edge.GetCurveParams3().StartPoint;
                                            //var endP = (double[])edge.GetCurveParams3().EndPoint;

                                            //txtInfo.Text = $@"Face {index} 边 {i+1}: 起点{stratP[0]},{stratP[1]},{stratP[2]}"   + System.Environment.NewLine + txtInfo.Text;
                                            //txtInfo.Text = $@"Face {index} 边 {i+1}: 终点{endP[0]},{endP[1]},{endP[2]}"   + System.Environment.NewLine + txtInfo.Text;
                                            

                                        }

                                    }

                                }



                            }
                        }
                        else
                        {
                            MessageBox.Show("请在特征树中选个特征。");
                        }

                     

                    }
                    finally
                    {

                        this.Visible = true;
                    }





                }


            }
            catch (Exception exception)
            {
                MessageBox.Show($@"{exception.StackTrace}");
            }
        }

        /// <summary>
        /// 打印边的信息
        /// </summary>
        /// <param name="swEdge"></param>
        /// <param name="txtBox"></param>
        private void PrintEdgeInfo(Edge swEdge,TextBox txtBox)
        {
            Curve swCurve = default(Curve);
            CurveParamData swCurveParaData = default(CurveParamData);
            swCurve = (Curve)swEdge.GetCurve();
            swCurveParaData = (CurveParamData)swEdge.GetCurveParams3();

            Debug.Print("The curve tag is: " + swCurveParaData.CurveTag);
            Debug.Print("The curve type as defined in swCurveType_e is: " + swCurveParaData.CurveType);

            double[] vEndPoint = null;
            vEndPoint = (double[])swCurveParaData.EndPoint;
            double[] EndPoint = new double[3];

            int i = 0;

            for (i = 0; i <= vEndPoint.GetUpperBound(0); i++)
            {
                EndPoint[i] = vEndPoint[i];
            }

            Debug.Print("The end point x,y,z coordinates are: " + EndPoint[0] + "," + EndPoint[1] + "," + EndPoint[2]);
            txtBox.Text = $@"边  终点{EndPoint[0]},{EndPoint[1]},{EndPoint[2]}"   + System.Environment.NewLine + txtBox.Text;
            double[] vStartPoint = null;
            double[] StartPoint = new double[3];
            vStartPoint = (double[])swCurveParaData.StartPoint;
            for (i = 0; i <= vStartPoint.GetUpperBound(0); i++)
            {
                StartPoint[i] = vStartPoint[i];
            }

            Debug.Print("The start point x,y,z coordinates are: " + StartPoint[0] + "," + StartPoint[1] + "," + StartPoint[2]);
            txtBox.Text = $@"边  起点{StartPoint[0]},{StartPoint[1]},{StartPoint[2]}" + System.Environment.NewLine + txtBox.Text;

        }

        private void btnPrintAllDims_Click(object sender, EventArgs e)
        {
            try
            {
                var swApp = Connect.GetRunningSolidWorks();

                txtInfo.Text = "";


                if (swApp == null)
                {
                    MessageBox.Show($@"请检查是否已经启动SolidWorks,并打开一个工程图。");

                    return;
                }

                var swModel = swApp.IActiveDoc2;

                if (swModel != null)
                {
                    try
                    {

                        if (swModel.GetType()!=(int)swDocumentTypes_e.swDocDRAWING)
                        {
                            MessageBox.Show($@"请打开一个工程图。");
                        }

                        var drawingDoc =(DrawingDoc) swModel;
                        var sheetNames = (string[])drawingDoc.GetSheetNames();
                        for (int i = 0; i < sheetNames.Length; i++)
                        {
                            var bActiveSheet = drawingDoc.ActivateSheet(sheetNames[i]);

                            if (bActiveSheet)
                            {

                                var sheet = drawingDoc.Sheet[sheetNames[i]];

                                //第一个是图纸页上的
                                var sheetView = (View)drawingDoc.GetFirstView();

                                if (sheetView != null)
                                {
                                    var swView = sheetView;
                                    var displayDimensions = (Object[])swView.GetDisplayDimensions();
                                    if (displayDimensions != null)
                                    {
                                        foreach (var displayDimension in displayDimensions)
                                        {
                                            var dim = (DisplayDimension)displayDimension;

                                            //Debug.Print(dim.GetNameForSelection());
                                            //Debug.Print(dim.GetDimension2(1).Value.ToString());
                                            txtInfo.Text = $@"尺寸名 {dim.GetNameForSelection()} 尺寸值 {dim.GetDimension2(1).Value}" + System.Environment.NewLine + txtInfo.Text;
                                        }
                                    }
                                }


                                var allViewsInThisSheet = (object[])sheet.GetViews();


                                foreach (var v in allViewsInThisSheet)
                                {
                                    var swView = (View)v;
                                    var displayDimensions = (Object[])swView.GetDisplayDimensions();
                                    if (displayDimensions!=null)
                                    {
                                        foreach (var displayDimension in displayDimensions)
                                        {
                                            var dim = (DisplayDimension)displayDimension;

                                            //Debug.Print(dim.GetNameForSelection());
                                            //Debug.Print(dim.GetDimension2(1).Value.ToString());
                                            txtInfo.Text = $@"尺寸名 {dim.GetNameForSelection()} 尺寸值 {dim.GetDimension2(1).Value}" + System.Environment.NewLine + txtInfo.Text;
                                        }
                                    }

                                    
                                }

                              


                            }

                        }

                        

                    }
                    finally
                    {

                        this.Visible = true;
                    }





                }


            }
            catch (Exception exception)
            {
                MessageBox.Show($@"{exception.StackTrace}");
            }
        }
    }
}